package comgutianyu.qihangjiaoyu;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import comgutianyu.qihangjiaoyu.adapter.LessonListAdapter;
import comgutianyu.qihangjiaoyu.model.LessonItem;

public class VideoPlayerActivity extends AppCompatActivity {
    
    private VideoView videoView;
    private SeekBar seekBar;
    private TextView currentTimeText;
    private TextView totalTimeText;
    private ImageButton playPauseButton;
    private TextView titleText;
    private static final Handler handler = new Handler(Looper.getMainLooper());
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_player);
        
        // 初始化视图
        initViews();
        // 设置点击事件
        setupClickListeners();
        // 设置视频播放
        setupVideoPlayer();
        // 设置课程列表
        setupLessonList();
    }
    
    private void initViews() {
        videoView = findViewById(R.id.videoView);
        seekBar = findViewById(R.id.seekBar);
        currentTimeText = findViewById(R.id.currentTimeText);
        totalTimeText = findViewById(R.id.totalTimeText);
        playPauseButton = findViewById(R.id.playPauseButton);
        titleText = findViewById(R.id.titleText);
        
        // 设置标题
        String title = getIntent().getStringExtra("title");
        titleText.setText(title != null ? title : "");
    }
    
    private void setupClickListeners() {
        // 返回按钮点击事件
        findViewById(R.id.backButton).setOnClickListener(v -> finish());
        
        // 播放/暂停按钮点击事件
        playPauseButton.setOnClickListener(v -> {
            if (videoView.isPlaying()) {
                videoView.pause();
                playPauseButton.setImageResource(R.drawable.ic_play);
            } else {
                videoView.start();
                playPauseButton.setImageResource(R.drawable.ic_pause);
            }
        });
    }
    
    private void setupVideoPlayer() {
        try {
            // 设置视频路径
            String videoPath = getIntent().getStringExtra("videoPath");
            videoView.setVideoPath(videoPath);
            
            // 设置错误监听
            videoView.setOnErrorListener((mp, what, extra) -> {
                // 显示错误提示
                Toast.makeText(this, "视频播放出错，请稍后重试", Toast.LENGTH_SHORT).show();
                return true;
            });
            
            // 准备完成后自动播放
            videoView.setOnPreparedListener(mediaPlayer -> {
                mediaPlayer.start();
                // 设置进度条最大值
                seekBar.setMax(mediaPlayer.getDuration());
                totalTimeText.setText(formatTime(mediaPlayer.getDuration()));
                
                // 开始更新进度
                updateProgress();
            });
            
            // 设置进度条变化监听
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if (fromUser) {
                        videoView.seekTo(progress);
                        currentTimeText.setText(formatTime(progress));
                    }
                }
                
                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {}
                
                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {}
            });
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "视频初始化失败", Toast.LENGTH_SHORT).show();
            finish();
        }
    }
    
    private void updateProgress() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (videoView.isPlaying()) {
                    int currentPosition = videoView.getCurrentPosition();
                    seekBar.setProgress(currentPosition);
                    currentTimeText.setText(formatTime(currentPosition));
                    handler.postDelayed(this, 1000);
                }
            }
        }, 1000);
    }
    
    private String formatTime(int milliseconds) {
        int seconds = milliseconds / 1000;
        int minutes = seconds / 60;
        int remainingSeconds = seconds % 60;
        return String.format("%02d:%02d", minutes, remainingSeconds);
    }
    
    private void setupLessonList() {
        RecyclerView recyclerView = findViewById(R.id.lessonListRecyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        
        // 创建测试数据
        List<LessonItem> lessonItems = new ArrayList<>();
        lessonItems.add(new LessonItem("第1讲 函数极限与连续三问解题法01", "11:38"));
        lessonItems.add(new LessonItem("第1讲 研究对象大观02", "01:01:04"));
        lessonItems.add(new LessonItem("第1讲 f(x)的性质03", "28:15"));
        lessonItems.add(new LessonItem("第1讲 变形04", "47:38"));
        lessonItems.add(new LessonItem("第2讲 导数与微分", "55:20"));
        lessonItems.add(new LessonItem("第3讲 中值定理与导数应用", "42:15"));
        lessonItems.add(new LessonItem("第4讲 不定积分的概念与性质", "38:45"));
        lessonItems.add(new LessonItem("第5讲 定积分的概念与性质", "45:30"));
        
        LessonListAdapter adapter = new LessonListAdapter(lessonItems);
        adapter.setOnItemClickListener((item, position) -> {
            // 处理课程点击事件
            titleText.setText(item.getTitle());
            // TODO: 加载对应的视频
        });
        
        recyclerView.setAdapter(adapter);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        videoView.stopPlayback();
    }
} 